package com.heima.admin.gateway.filter;


import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author shitou
 * @className AuthorizationFilter
 * @description: TODO
 */
@Component
@Slf4j
public class AuthorizationFilter implements GlobalFilter, Ordered {

    /**
     * admin用户管理网关
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("用户平台管理登录过滤--start");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 登录路径放行
        String path = request.getURI().getPath();
        log.info("path:{}", path);
        if (StringUtils.contains(path, "/login")) {
            return chain.filter(exchange);
        }
        // 获取携带的token
        String token = request.getHeaders().getFirst("token");
        // 为空
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 校验token
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        // 过期返回
        int flag = AppJwtUtil.verifyToken(claimsBody);
        if (flag == 1 || flag == 2) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 解析token获取用户id
        Object id = claimsBody.get("id");
        // 重新封装header
        ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
            httpHeaders.add("userId", id + "");
        }).build();
        // 重置header
        exchange.mutate().request(serverHttpRequest);
        // token 有效 放行
        log.info("token有效已放行");
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
